//
//  AYuOAuthViewController.swift
//  SHWeibo3
//
//  Created by 余伟康 on 16/7/20.
//  Copyright © 2016年 wangce. All rights reserved.
//

import UIKit
import SVProgressHUD

class AYuOAuthViewController: UIViewController {

    override func loadView() {
        // 请求的url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREIRECT_URI)"
        // 初始化一个url
        let url = NSURL(string: urlString)
        guard let u = url else{
            return
        }
        // 初始化一个request
        let request = NSURLRequest(URL: u)
        // webView 加载request
        webView.loadRequest(request)
        webView.delegate = self
        view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        progressView.removeFromSuperview()
    }
    
    // MARK: - 设置界面
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
        
        setupNav()
    }
    
    // MARK: - 设置导航
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: "autoFillClick")
        navigationItem.title = "微博登录"
    }
    
    // MARK: - 监听事件
    
    // 取消
    @objc private func cancelClick(){
        // 关闭控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 自动填充
    @objc private func autoFillClick(){
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - 懒加载控件
    // webView
    private lazy var webView:UIWebView = UIWebView()
    // 进度条
    private lazy var progressView:AYuOAuthProgressView = AYuOAuthProgressView()
}


// MARK: - UIWebViewDelegate
extension AYuOAuthViewController :UIWebViewDelegate{

    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.satrtAnim()
    }
    
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.endAnim()
    }
    
    // 监听webView
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("监听webView")
        let urlString = request.URL?.absoluteString
        if let u = urlString where u.hasPrefix(APPREIRECT_URI){
            // url 的 请求参数
            let query = request.URL?.query
            if let q = query{
                // 获取code
                print(q)
                let code = q.substringFromIndex("code=".endIndex)
                print(code)
                
                
                AYuUserAccountViewModel.sharedTools.loadUserAccount(code,isSuccess:{(isSucc)->() in
                    print(isSucc)
                    
                    if !isSucc{
                        print("---->请求失败")
                        return
                    }
                    
                    // 先关闭页面
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        // 发送一个通知 告知appdelegate 切换根控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                    })
                    
                })
                return false
            }
        }
        return true
    }
    
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("webView加载失败")
    }
    
}


// MARK: - 请求数据
extension AYuOAuthViewController {
    // 请求accessToken
    func getUserAccount(code: String){
        
        AYuNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            // 当在guard 或者if let中 使用as  一般情况下 都是使用as?
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
                return
            }
            // 字典转模型
            let userAccount = AYuUserAccount(dict: res)
            self.getUserInfo(userAccount)
            }) { (error) -> () in
                print("请求失败\(error)")
        }
        
        
    }
    // 获取用户信息数据
    func getUserInfo(userAccount: AYuUserAccount){
        
        AYuNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            // 判断response是否为nil 而且是否可以转成字典
            guard let res = response as? [String: AnyObject] else{
                return
            }
            // 因为当前的screenname 和avatar_large 本来就是可选值 所以在as的时候 只用as? 转字符串
            // 给其userAccount身上两个为nil的属性赋值
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            print(userAccount)
            }) { (error) -> () in
                print("请求失败:\(error)")
        }
    }
}

